package org.conan.groupapp.framework.action;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.conan.groupapp.framework.entity.ParamBean;
import org.conan.groupapp.framework.service.IBaseService;
import org.conan.groupapp.system.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.ui.Model;

/**
 * 基础类
 * @author pengjun
 */
public abstract class BaseAction<T extends ParamBean>{
	private static final long serialVersionUID = -3989138693556898925L;
	public static final String USER_SESSION_NAME = "current_user";
	protected IBaseService<T> iBaseService;
	@Autowired
	private SessionRegistry sessionRegistry;
	

	public IBaseService<T> getiBaseService() {
		return iBaseService;
	}

	public void setiBaseService(IBaseService<T> iBaseService) {
		this.iBaseService = iBaseService;
	}
	/**
	 * 获取当请登录用户
	 * @param request
	 * @return
	 */
	protected User loadCurrentUser(HttpServletRequest request){
		return (User)request.getSession().getAttribute(USER_SESSION_NAME);
	}
	
	/**
	 * 列出所有在线用户
	 * <c:forEach items="${activeUsers}" var="uinfo">
     *	<li><strong>${uinfo.key.username}</strong> 
     *	/ Last Active: <strong>${uinfo.value}</strong></li>
  	 *	</c:forEach>
	 * @param model
	 */
	//@RequestMapping("/listActiveUsers")
	public Map<Object,Date> listActiveUsers(Model model){
		Map<Object,Date> lastActivityDates = new HashMap<Object,Date>();
		for (Object principal:sessionRegistry.getAllPrincipals()) {
			//a principal may have multiple active sessions
			for(SessionInformation session : sessionRegistry.getAllSessions(principal, false)){
				// no last activity stored
				if(lastActivityDates.get(principal) == null) {
				      lastActivityDates.put(principal, session.getLastRequest());
				} else {
				    // check to see if this session is newer than the last stored
					Date prevLastRequest = lastActivityDates.get(principal);
				    if(session.getLastRequest().after(prevLastRequest)) {
				          // update if so
				    	lastActivityDates.put(principal, 
				        session.getLastRequest());
				    }
				}
			}
		}
		return lastActivityDates;
		//model.addAttribute("activeUsers",lastActivityDates);
	}
	
	/**
	 * 获取在线用户数
	 * @return
	 */
	//@ModelAttribute("numUsers")
	public int loadNumberOfUsers(){
		return sessionRegistry.getAllPrincipals().size();
	}
	
	public SessionRegistry getSessionRegistry() {
		return sessionRegistry;
	}

	public void setSessionRegistry(SessionRegistry sessionRegistry) {
		this.sessionRegistry = sessionRegistry;
	}
	
}